﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NT40Redis.Models;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Redis;
using Microsoft.AspNetCore.Http;

namespace NT40Redis.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            //向session中保存数据
            HttpContext.Session.SetString("mysession",$"你好！张三{DateTime.Now}");
            ViewBag.Msg = "数据缓存成功";


            //使用session
            // RedisCacheOptions options = new RedisCacheOptions();
            // options.Configuration = "127.0.0.1:6379";//访问连接
            // options.InstanceName = "myredis";//
            // var redisClient = new RedisCache(options);//创建对象
            // //redisClient.SetString("name",$"张三!{DateTime.Now}");
            // //在创建的时候 设置过期时间
            ////SetAbsoluteExpiration 绝对过期时间
            // redisClient.SetString("name1", $"张三1!{DateTime.Now}",new DistributedCacheEntryOptions().SetAbsoluteExpiration(DateTime.Now.AddMinutes(2)));
            // //相对过期时间
            // redisClient.SetString("name2", $"张三2!{DateTime.Now}", new DistributedCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMilliseconds(2)));

            return View();
        }

        public IActionResult Privacy()
        {
            //读取session
            var result = HttpContext.Session.GetString("mysession");
            ViewBag.Msg = $"数据缓存成功{result}";

            //读取redis
            // RedisCacheOptions options = new RedisCacheOptions();
            // options.Configuration = "127.0.0.1:6379";//访问连接
            // options.InstanceName = "myredis";//
            // var redisClient = new RedisCache(options);//创建对象
            // //读取数据
            //var result= redisClient.GetString("name");
            // var result1 = redisClient.GetString("name1");
            // var result2 = redisClient.GetString("name2");
            //ViewBag.Msg = $"数据缓存成功{result}，{result1}-----{result2}" ;
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
